package com.wzq.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wzq.dao.pojo.*;
import com.wzq.service.IAchievementService;
import com.wzq.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/achievement")
public class AdminAchievementController extends GetSome{

    @Autowired
    IAchievementService iAchievementService;
    @RequestMapping("/list")
    public R list(@RequestBody PageBean pageBean){
        System.out.println(pageBean);
        String query=pageBean.getQuery().trim();
        Page<Achievement> page=new Page<>(pageBean.getPageNum(),pageBean.getPageSize());
        



        Page<Achievement> pageResult = iAchievementService.page(page, new QueryWrapper<Achievement>().in(StringUtil.isNotEmpty(query), "p_id", searchByPname(query)));
        //        添加用户名称和项目名称
        List<Achievement> list=new ArrayList<>();
        for (Achievement achievement : pageResult.getRecords()) {
            achievement.setP_name( getP_name(achievement.getP_id()) );
            achievement.setAscription_name( getP_name(achievement.getAscription()));
            list.add(achievement);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("AchievementList",list);
        map.put("total",pageResult.getTotal());
        return R.ok(map);
    }

    @RequestMapping("/save")
    public R save(@RequestBody Achievement achievement){
        if(achievement.getId()==null || achievement.getId()==-1){
                iAchievementService.save(achievement);
        }else{
            if (super.iProjectService.getById(achievement.getP_id()) != null) {
                iAchievementService.saveOrUpdate(achievement);
            }else {
                return  R.error(Code.UPDATE_ERR,"用户不存在，请重新输入！");
            }
        }
        return R.ok();
    }

    @GetMapping("/{id}")
    public R findById(@PathVariable(value = "id")Integer id){
        Achievement achievement = iAchievementService.getById(id);
        //        获得用户名称和项目名称
        achievement.setP_name( getP_name(achievement.getP_id()) );
        Map<String,Object> map=new HashMap<>();
        map.put("achievement",achievement);
        return R.ok(map);
    }

    @GetMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id")Integer id){
        iAchievementService.removeById(id);
        return R.ok();
    }

    @RequestMapping("/listAll")
    public R listAll(){
        Map<String,Object> map=new HashMap<>();
        map.put("AchievementList",iAchievementService.list());
        return R.ok(map);
    }


}

